﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.MultiTenancy;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using Microsoft.EntityFrameworkCore;
using Mt.Site.Core.BackGroundJobs.Entities;
using Mt.Site.Core.WorkFlows.Process;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Core.BackGroundJobs
{
    public class WorkFlowPeriodicNoticeWorker : AsyncPeriodicBackgroundWorkerBase, ISingletonDependency
    {
        public const bool IsEnabled = false;

        private const int CheckPeriodAsMilliseconds = 1 * 1000 * 60; // 1min
        private readonly IRepository<PeriodicBackgroundJobLog, long> _periodicBackgroundJobLogRepository;
        private readonly IWorkFlowSuperManager _workFlowSuperManager;

        public WorkFlowPeriodicNoticeWorker(
            AbpAsyncTimer timer,
            IRepository<PeriodicBackgroundJobLog, long> periodicBackgroundJobLogRepository,
            IWorkFlowSuperManager workFlowSuperManager) 
            : base(timer)
        {
            _periodicBackgroundJobLogRepository = periodicBackgroundJobLogRepository;
            _workFlowSuperManager = workFlowSuperManager;

            LocalizationSourceName = MtSiteConsts.LocalizationSourceName;

            Timer.Period = CheckPeriodAsMilliseconds;
            Timer.RunOnStart = true;
        }

        protected override async Task DoWorkAsync()
        {
            var now = DateTime.Now;
            string dateStr = now.ToString("yyyy-MM-dd");

            if (now.IsBetween(
                new DateTime(now.Year, now.Month, now.Day, 14, 30, 0, DateTimeKind.Local),
                new DateTime(now.Year, now.Month, now.Day, 14, 35, 0, DateTimeKind.Local))
                )
            {
                await UnitOfWorkManager.WithUnitOfWorkAsync(async () => {
                    using (CurrentUnitOfWork.SetTenantId(MultiTenancyConsts.DefaultTenantId))
                    {
                        var finishedNameList = await GetAllLogDataTodayAsync(dateStr);

                        if (!finishedNameList.Contains("RemoveTemporaryPaper"))
                        {
                            await AddLogs("RemoveTemporaryPaper", "", dateStr);

                            await _workFlowSuperManager.RemoveTemporaryPaperAsync();
                        }
                    }
                });
            }
        }

        private async Task<List<string>> GetAllLogDataTodayAsync(string dateStr)
        {
            var query = from log in _periodicBackgroundJobLogRepository.GetAll()
                        where log.Date == dateStr
                        select log.TaskName;
            return await query.ToListAsync();
        }

        private async Task<long> AddLogs(string taskName, string customData, string dateStr)
        {
            var entity = new PeriodicBackgroundJobLog
            {
                Date = dateStr,
                TaskName = taskName,
                FinishTime = DateTime.Now,
                CustomData = customData
            };

            await _periodicBackgroundJobLogRepository.InsertAsync(entity);

            await UnitOfWorkManager.Current.SaveChangesAsync();

            return entity.Id;
        }
    }
}
